package com.dyw.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dyw.blog.dao.dos.Archives;
import com.dyw.blog.dao.entity.*;
import com.dyw.blog.dao.mapper.ArticleBodyMapper;
import com.dyw.blog.dao.mapper.ArticleMapper;
import com.dyw.blog.dao.mapper.ArticleTagMapper;
import com.dyw.blog.service.*;
import com.dyw.blog.utils.UserThreadLocal;
import com.dyw.blog.vo.ArticleBodyVo;
import com.dyw.blog.vo.ArticleVo;
import com.dyw.blog.vo.TagVo;
import com.dyw.blog.vo.params.ArticleParam;
import com.dyw.blog.vo.params.PageParams;
import com.dyw.blog.vo.Result;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author Devil
 * @create 2022-02-10 16:28
 */
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private TagService tagService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ArticleBodyMapper articleBodyMapper;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ThreadService threadService;
//    @Autowired
//    private ArticleTagMapper articleTagMapper;


//    @Override
//    public Result listArticle(PageParams pageParams) {
//        /**
//         * 1. 分页查询article数据库表
//         */
//        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
//        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
//        //查询文章的参数 加上分类id, 判断不为空 加上分类条件
//        if(pageParams.getCategoryId()!=null){
//            queryWrapper.eq(Article::getCategoryId,pageParams.getCategoryId());
//        }
//        ArrayList<Long> articleIdList = new ArrayList<>();
//        if(pageParams.getTagId()!=null){
//            /**加入标签条件查询
//             * article表中并没有tag字段 一篇文章有多个标签
//             * article_tag article_id 1:n tag_id
//             * 我们需要利用一个全新的属于文章标签的queryWrapper将这篇文章article_Tag查出来,保存到一个list当中
//             * 然后再根据queryWrapper的in方法选择我们需要的标签即可
//             */
//            LambdaQueryWrapper<ArticleTag> articleTagLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            articleTagLambdaQueryWrapper.eq(ArticleTag::getTagId,pageParams.getTagId());
//            List<ArticleTag> articleTags = articleTagMapper.selectList(articleTagLambdaQueryWrapper);
//            for (ArticleTag articleTag : articleTags) {
//                articleIdList.add(articleTag.getArticleId());
//            }
//            if(articleTags.size()>0){
//                queryWrapper.in(Article::getId,articleIdList);
//            }
//        }
//        //按照创建日期倒叙排序
//        //是否置顶排序
//        queryWrapper.orderByDesc(Article::getWeight, Article::getCreateDate);
//        Page<Article> articlePage = articleMapper.selectPage(page, queryWrapper);
//        List<Article> records = articlePage.getRecords();
//        //能直接返回吗 需要一个vo对象来存储筛选显示的数据
//        List<ArticleVo> articleVoList = copyList(records,true,true);
//        return Result.success(articleVoList);
//    }

    @Override
    public Result listArticle(PageParams pageParams) {
        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
        IPage<Article> articleIPage = articleMapper.listArticle(page,
                pageParams.getCategoryId(),
                pageParams.getTagId(),
                pageParams.getYear(),
                pageParams.getMonth());
        List<Article> records = articleIPage.getRecords();
        return Result.success(copyList(records,true,true));
    }

    @Override
    public Result hotArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getViewCounts).select(Article::getId,Article::getTitle).last("limit "+ limit);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        return Result.success(copyList(articles,false,false));
    }

    @Override
    public Result newArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getCreateDate).select(Article::getId,Article::getTitle).last("limit "+ limit);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        return Result.success(copyList(articles,false,false));
    }

    @Override
    public Result listArchives() {
        List<Archives> archivesList = articleMapper.listArchives();
        return Result.success(archivesList);

    }

    /**
     * 1. 根据id查询 文章信息
     * 2. 根据bodyid和catagroryid 去做关联查询
     * @param id
     * @return
     */
    @Override
    public Result findArticleById(long id) {
        Article article = articleMapper.selectById(id);
        ArticleVo articleVo = copy(article,true,true,true,true);
        //查看玩文章了,新增阅读数
        //查看完文章之后,本应该直接返回数据了 这时候租了一个更新操作,更新时加写锁,阻塞了其他的读操作,性能就会比较低
        //更新增加了此次接口的 耗时 如果一旦更新出问题 不能影响 查看文章的操作
        //使用线程池 可以把更新操作扔到线程池中执行 和主线程就不相关了
        threadService.updateArticleViewCount(articleMapper,article);
        return Result.success(articleVo);
    }


    private List<ArticleVo> copyList(List<Article> records,boolean isTag,boolean isAuthor) {
        ArrayList<ArticleVo> articleVos = new ArrayList<>();
        for (Article record : records) {
            articleVos.add(copy(record,isTag,isAuthor));
        }
        return articleVos;
    }

    private ArticleVo copy(Article article,boolean isTag,boolean isAuthor) {
        ArticleVo articleVo = new ArticleVo();
        articleVo.setId(String.valueOf(article.getId()));
        BeanUtils.copyProperties(article, articleVo);
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm:ss"));
        if(isTag){
            articleVo.setTags(tagService.findTagsByArticleId(article.getId()));
        }
        if(isAuthor){
            articleVo.setAuthor(sysUserService.findUserById(article.getAuthorId()).getNickname());
        }
        return articleVo;
    }

    private ArticleVo copy(Article article,boolean isTag,boolean isAuthor,boolean isBody,boolean isCategory) {
        ArticleVo articleVo = new ArticleVo();
        articleVo.setId(String.valueOf(article.getId()));
        BeanUtils.copyProperties(article, articleVo);

        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm:ss"));
        if(isTag){
            articleVo.setTags(tagService.findTagsByArticleId(article.getId()));
        }
        if(isAuthor){
            articleVo.setAuthor(sysUserService.findUserById(article.getAuthorId()).getNickname());
        }
        if(isBody){
            Long articleBodyId = article.getBodyId();
            articleVo.setBody(findArticleBodyById(articleBodyId));
        }
        if(isCategory){
            Long categoryId = article.getCategoryId();
            articleVo.setCategory(categoryService.findCategoryById(categoryId));
        }
        return articleVo;
    }


    @Override
    public ArticleBodyVo findArticleBodyById(Long id) {
        ArticleBody articleBody = articleBodyMapper.selectById(id);
        ArticleBodyVo articleBodyVo = new ArticleBodyVo();
        articleBodyVo.setContent(articleBody.getContent());
        return articleBodyVo;
    }

    @Override
    public Result publishArticle(ArticleParam articleParam) {
        //发布文章 前提 需要已登录 所以需要将接口加入拦截器中
        SysUser sysUser = UserThreadLocal.get();
        /**
         * 1.发布文章 实际上就是 构建一个Article对象 然后再插入表中
         * 2. 作者id 当前登陆用户的id
         * 3. 标签 要将标签加入到关联列表当中
         * 4. body 内容存储 article bodyId
         */
        Article article = new Article();
        article.setAuthorId(sysUser.getId());
        article.setCategoryId(Long.parseLong(articleParam.getCategory().getId()));
        article.setCreateDate(System.currentTimeMillis());
        article.setViewCounts(0);
        article.setSummary(articleParam.getSummary());
        article.setTitle(articleParam.getTitle());
        article.setCommentCounts(0);
        article.setWeight(Article.ARTICLE_COMMON);
        article.setBodyId(-1L);
        //文章id自动生成 雪花算法
        articleMapper.insert(article);

        //tags
        List<TagVo> tags = articleParam.getTags();
        if(tags!=null){
            for (TagVo tag : tags) {
                ArticleTag articleTag = new ArticleTag();
                articleTag.setArticleId(article.getId());
                articleTag.setTagId(Long.parseLong(tag.getId()));
                tagService.save(articleTag);
            }
        }

        //body
        ArticleBody articleBody = new ArticleBody();
        articleBody.setArticleId(article.getId());
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        articleBodyMapper.insert(articleBody);


        //根据结构 我们需要再article中设置bodyId Mybatis-plus中会将更新的数据赋值给对象
        //这里的id我们并没有设置 而是雪花算法 插入之后 数据库的id赋值给了对象 我们可以通过这个对象获取
        article.setBodyId(articleBody.getId());

        //将文章更新
        articleMapper.updateById(article);


        //接口要求返回articleVo对象
        ArticleVo articleVo = new ArticleVo();
        articleVo.setId(String.valueOf(article.getId()));
        return Result.success(articleVo);
    }
}
